//
//  SettingListViewController.swift
//  CheckmeRing
//
//  Created by 董鹏 on 2022/2/14.
//

import UIKit

/// 数据源初始化
private struct SettingConfig {
    var name: String
    var content: String
    var showSwitch: Bool
    var type: SettingType?
}

private enum SettingType {
    case ScreenMode // 正常/常亮
    case ScreenBrightness // 显示亮度
    case FactoryReset // 复位
    case DeviceUpdate // Ring升级
    case AutomicConnect // 自动连接
    case AppleHealth // 苹果健康
    case SelectDevice // 选择查看的设备数据
    case Help // 帮助
    case About // 关于
    case Cloud // 同步
}

class SettingListViewController: RViewController, SettingTableViewCellDelegate {
    
    private var topData = [SettingConfig]()
    private var bottomData = [SettingConfig]()
    private var allData = [[SettingConfig]]()
    // 标记是否返回导航条动画
    private var backAnimation = false
    
    /// 当前链接设备名称
    @IBOutlet weak var deviceNameLabel: UILabel!
    @IBOutlet weak var settingLabelMarginBottom: NSLayoutConstraint!
    @IBOutlet weak var navigationHeight: NSLayoutConstraint!
    @IBOutlet weak var tableView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.navigationHeight.constant = 44 + getStatusBarHight()
        self.view.backgroundColor = hexColor("F9F9F9")
        self.tableView.backgroundColor = self.view.backgroundColor
        self.tableView.tableFooterView = UIView()
        self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 15))
        
    }
    
    func initData() {
        allData.removeAll()
        
        var ScreenMode = ""
        var LightStrength = ""
        if let info = RManager.manager.info {
            // 0-Standard, 1-Always off, 2-Always on.
            ScreenMode = Int(info.lightingMode) == 0 ? "標準" : "常にオン"
            // 2-High    1-Medium     0-Low
            if info.lightStrength == "0" {
                LightStrength = "低"
            }else if info.lightStrength == "1" {
                LightStrength = "中"
            }else {
                LightStrength = "高"
            }
            
            var result = info.sn
            if result.contains("CRL") || result.contains("CRS") || result.contains("crl") || result.contains("crs") {
                result.removeFirst()
                result.removeFirst()
                result.removeFirst()
            }
            self.deviceNameLabel.text = (RManager.manager.isBig ? "CMRing" : "CMRingS") + result
        }
        
        topData.removeAll()
        topData.append(SettingConfig.init(name: "画面モード", content: ScreenMode, showSwitch: false, type: SettingType.ScreenMode))
        topData.append(SettingConfig.init(name: "画面の明るさ", content: LightStrength, showSwitch: false, type: SettingType.ScreenBrightness))
        topData.append(SettingConfig.init(name: "工場出荷状態リセット", content: "", showSwitch: false, type: SettingType.FactoryReset))
        topData.append(SettingConfig.init(name: "デバイスアップデート", content: "", showSwitch: false, type: SettingType.DeviceUpdate))
        
        if RManager.manager.currentDevice != nil {
            allData.append(topData)
        }
        
        
        bottomData.removeAll()
        bottomData.append(SettingConfig.init(name: "自動接続", content: "", showSwitch: true, type: SettingType.AutomicConnect))
        bottomData.append(SettingConfig.init(name: "Appleヘルスケアとの連携", content: "", showSwitch: true, type: SettingType.AppleHealth))
        
        /// 没有设备链接，并且保存过历史设备
        if RManager.manager.currentDevice == nil, let historyDevice = RManager.manager.currentHistoryDevice {
            
            bottomData.append(SettingConfig.init(name: "デバイスを選択", content: historyDevice.advName, showSwitch: false, type: SettingType.SelectDevice))
        }
        
        bottomData.append(SettingConfig.init(name: "ヘルプ", content: "", showSwitch: false, type: SettingType.Help))
        bottomData.append(SettingConfig.init(name: "CheckmeRingについて", content: "", showSwitch: false, type: SettingType.About))
        bottomData.append(SettingConfig.init(name: "クラウド", content: "", showSwitch: false, type: SettingType.Cloud))
        allData.append(bottomData)
        
        self.tableView.reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.setNavigationBarHidden(true, animated: self.backAnimation)
        
        // 后台重回前台
        NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        self.refreshState()
    }
    
    @objc func appDidBecomeActive() {
        self.refreshState()
    }
    
    func refreshState() {
        /// 顶部标题下的设备名称
        if RManager.manager.currentDevice != nil {
            self.settingLabelMarginBottom.constant = 22
        }else {
            self.deviceNameLabel.text = ""
            self.settingLabelMarginBottom.constant = 10
        }
        
        self.initData()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.backAnimation = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.setNavigationBarHidden(false, animated: true)
        NotificationCenter.default.removeObserver(self)
    }
    
}

extension SettingListViewController: UITableViewDelegate, UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return allData.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return allData[section].count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tableView.dequeueReusableCell(withIdentifier: "SettingTableViewCell") as!  SettingTableViewCell
        cell.selectionStyle = .none
        
        let config = allData[indexPath.section][indexPath.row]
        
        // 由于虚线条是自定义的，所以要设置
        cell.separLine.isHidden = indexPath.row == allData[indexPath.section].count - 1
        
        // 设置数据
        cell.indexPath = indexPath
        cell.titleLabel.text = config.name
        cell.contentLabel.text = config.content
        // 是否显示开关按钮
        cell.stateSwitch.isHidden = !config.showSwitch
        cell.delegate = self
        
        // 是否显示右箭头
        cell.rightDisclosure.isHidden = config.showSwitch
        
        // 自动链接的开关
        if config.type == .AutomicConnect {
            cell.stateSwitch.isOn = CacheManager.manager.getValueForKey(AutoConnect) as? Bool ?? true
        }
        
        // 苹果健康的开关
        if config.type == .AppleHealth {
            cell.stateSwitch.isOn = CacheManager.manager.getValueForKey(AppleHealthUpload) as? Bool ?? false
        }
        
        return cell
    }
    
//    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
//
//        if let cell = cell as? SettingTableViewCell {
//            // 如果是最后一行
//            var corner:CGFloat = 0
//            if indexPath.row == self.allData[indexPath.section].count - 1 {
//                corner = 8
//            }
//            cell.bgView.clipsToBounds = true
//            cell.bgView.maskCorners(corners: UIRectCorner.init(rawValue: UIRectCorner.bottomLeft.rawValue | UIRectCorner.bottomRight.rawValue), cornerRadi: corner)
//        }
//
//    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
//        if RManager.manager.currentDevice == nil, indexPath.section == 0 {
//            self.view.makeToast("デバイスリンクなし", point: self.view.center, title: nil, image: nil, completion: nil)
//            return
//        }
        
        self.backAnimation = true
        let config = allData[indexPath.section][indexPath.row]
        var vc = RViewController()
        switch config.type {
        case .ScreenMode: // 是否常亮
            vc = getStoryBoardVC(identifier: "ScreenModeViewController")
            
        case .ScreenBrightness: // 屏幕亮度
            vc = getStoryBoardVC(identifier: "ScreenBrightnessViewController")
            
        case .FactoryReset: // 回复出厂设置 删除所有数据
            vc = getStoryBoardVC(identifier: "FactoryResetViewController")
        case .DeviceUpdate:
            vc = getStoryBoardVC(identifier: "DeviceUpdateViewController")
        case .SelectDevice:
            vc = getStoryBoardVC(identifier: "HistoryDeviceListVC")
        case .Help:
            vc = getStoryBoardVC(identifier: "PrivacyViewController")
        case .About:
            vc = getStoryBoardVC(identifier: "AboutViewController")
        case .Cloud:
            vc = getStoryBoardVC(identifier: "CloudViewController")
        default:
            return
        }
        vc.title = config.name
        vc.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    /// 开关按钮发生变化
    func returnSwitchStateAndIndexPath(_ indexPath: IndexPath, state: Bool) {
        let config = allData[indexPath.section][indexPath.row]
        // 自动链接
        if config.type == .AutomicConnect {
            CacheManager.manager.setValueForKey(AutoConnect, state as NSCoding)
        }
        
        // 苹果健康
        if config.type == .AppleHealth {
            CacheManager.manager.setValueForKey(AppleHealthUpload, state as NSCoding)
            if state == true {
                HealthTool.openPermissions()
            }
        }
        
        // 按设备自动链接的
//        RManager.manager.currentDevice?.automicConnect = state
//        var history = CacheManager.manager.getValueForKey(HistoryDevice) as! [VTDevice]
//        var hadIndex = 0
//        // 找到已保存设备列表中对应的设备，修改状态并保存
//        for (index, obj) in history.enumerated(){
//            if obj.identifiers == RManager.manager.currentDevice?.identifiers {
//                hadIndex = index
//                break
//            }
//        }
//        history[hadIndex] = RManager.manager.currentDevice!
//        CacheManager.manager.setValueForKey(HistoryDevice, history as NSCoding)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 43
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 35
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 15
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.width, height: 35))
        view.maskCorners(corners: UIRectCorner.init(rawValue: UIRectCorner.topLeft.rawValue | UIRectCorner.topRight.rawValue), cornerRadi: 8)
        view.layer.masksToBounds = true
        view.backgroundColor = UIColor.white
        let label = UILabel.init(frame: CGRect(x: 10, y: 0, width: 100, height: view.height))
        label.textColor = hexColor("3468E2")
        label.font = mediumFont(size: 15)
        label.text = ["デバイス", "一般"][section]
        if allData.count == 1 {
            label.text = "一般"
        }
        view.addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.width, height: 15))
        return view
    }
    
}
